package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ForkJoinPool;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import static com.ruoyi.system.utils.draw.overpng;
import static com.ruoyi.system.utils.draw.overpngbyX_Y;
import static com.ruoyi.system.utils.resultmap.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@Service
public class ScaleRecordServiceImpl implements IScaleRecordService
{
    @Autowired
    private ScaleRecordMapper scaleRecordMapper;

    @Autowired
    private ScaleMapper scaleMapper;

    @Autowired
    private ScaleV2Mapper scaleV2Mapper;

    @Autowired
    private PenJsonMapper penJsonMapper;

    @Autowired
    private PenJsonV2Mapper penJsonV2Mapper;

    @Autowired
    private IPenJsonService iPenJsonService;

    @Autowired
    private IPenJsonV2Service iPenJsonV2Service;

    @Autowired
    private IScrTotalService scrTotalService;

    @Autowired
    private IScrTotalV2Service scrTotalV2Service;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInfoV2Service userInfoV2Service;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ScaleRecord selectScaleRecordById(Long id)
    {
        return scaleRecordMapper.selectScaleRecordById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param scaleRecord 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ScaleRecord> selectScaleRecordList(ScaleRecord scaleRecord)
    {
        return scaleRecordMapper.selectScaleRecordList(scaleRecord);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param scaleRecord 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertScaleRecord(ScaleRecord scaleRecord)
    {
        return scaleRecordMapper.insertScaleRecord(scaleRecord);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param scaleRecord 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateScaleRecord(ScaleRecord scaleRecord)
    {
        return scaleRecordMapper.updateScaleRecord(scaleRecord);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteScaleRecordByIds(Long[] ids)
    {
        return scaleRecordMapper.deleteScaleRecordByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteScaleRecordById(Long id)
    {
        return scaleRecordMapper.deleteScaleRecordById(id);
    }

    @Override
    public int insertScalerecordcomplex(ScaleRecord scaleRecord) {
        scaleRecord.setStatus(0l);
        return scaleRecordMapper.insertScaleRecord(scaleRecord);
    }

    @Override
    public void handelscale() throws JsonProcessingException {
        System.out.println("handling scale");
        ScaleRecord scaleRecord = new ScaleRecord();
        scaleRecord.setStatus(0l);
        List<ScaleRecord> scaleRecords = scaleRecordMapper.selectScaleRecordList(scaleRecord);
        for(ScaleRecord scr:scaleRecords){
            PenJson penJson = new PenJson();
            penJson.setScrId(scr.getId());
            penJsonMapper.insertPenJson(penJson);
            scr.setStatus(1l);
            scaleRecordMapper.updateScaleRecord(scr);
        }

/*        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.submit(() ->
                scaleRecords.parallelStream().forEach(scr -> {

                })
        ).join();
        forkJoinPool.shutdown();*/
        for (ScaleRecord scr:scaleRecords){
            String str = "";
            try {
                JSONArray jsonArray = new JSONArray(scr.getJson());
                Map<Integer,JSONArray> map = new HashMap<>();

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONArray subArray = jsonArray.getJSONArray(i);
                    for (int j = 0; j < subArray.size(); j++) {
                        JSONObject point = subArray.getJSONObject(j);
                        int page_id = (int) point.get("page_id");
                        if(map.containsKey(page_id)){
                            JSONArray tempjsonarray = map.get(page_id);
                            tempjsonarray.put(point);
                            map.put(page_id,tempjsonarray);
                        }
                        else {
                            JSONArray tempjsonarray = new JSONArray();
                            tempjsonarray.put(point);
                            map.put(page_id,tempjsonarray);
                        }
                    }
                }
                //json分页

                for (Map.Entry<Integer, JSONArray> entry : map.entrySet()) {
                    Integer i = entry.getKey();
                    Scale scaletemp = scaleMapper.selectScaleById(Long.valueOf(i));
                    String folderpath = Constants.BASE_DIR+scr.getId()+File.separator;
                    File sourceFolder = new File(folderpath);
                    if (!sourceFolder.exists()) {
                        sourceFolder.mkdirs();
                    }
                    //存笔迹  service引入另一个servie
                    PenJson penJson = new PenJson();
                    penJson.setScrId(scr.getId());
                    List<PenJson> penJsons = penJsonMapper.selectPenJsonList(penJson);
                    iPenJsonService.insertpenjson(entry.getValue().toString(),Long.valueOf(entry.getKey().toString()),penJsons.get(0));
                    overpng(entry.getValue().toString(),folderpath+scr.getId()+"_"+entry.getKey()+".png",scaletemp.getX().intValue(),scaletemp.getY().intValue());
                    String outputPATH=Constants.NGINX_DIR+scr.getId()+"_"+entry.getKey()+".png";
//                    if(entry.getKey()==54761||entry.getKey()==54768){
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);
//                    }
                    if(entry.getKey()==55246l){//entry.getKey()==54400||entry.getKey()==54258||entry.getKey()==54259
                        //System.out.println(outputPATH);
                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);

                        String DetecteResult=OCR.GeneralHandwritingOCR(outputPATH);
                        //String DetecteResult="{\"Response\":{\"Angel\":359.989990234375,\"RequestId\":\"f5a50fa8-fdaf-4d0c-b9a7-1caf93679fdb\",\"TextDetections\":[{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":1}}\",\"Confidence\":100,\"DetectedText\":\"姓名\",\"Polygon\":[{\"X\":260,\"Y\":198},{\"X\":405,\"Y\":210},{\"X\":395,\"Y\":320},{\"X\":251,\"Y\":307}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"女\",\"Polygon\":[{\"X\":703,\"Y\":212},{\"X\":815,\"Y\":212},{\"X\":815,\"Y\":312},{\"X\":703,\"Y\":312}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"123456789\",\"Polygon\":[{\"X\":848,\"Y\":235},{\"X\":1267,\"Y\":263},{\"X\":1255,\"Y\":435},{\"X\":836,\"Y\":407}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"2004-08-25\",\"Polygon\":[{\"X\":1203,\"Y\":215},{\"X\":1303,\"Y\":202},{\"X\":1318,\"Y\":310},{\"X\":1217,\"Y\":323}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":5}}\",\"Confidence\":99,\"DetectedText\":\"2004\",\"Polygon\":[{\"X\":1611,\"Y\":224},{\"X\":1773,\"Y\":224},{\"X\":1773,\"Y\":324},{\"X\":1611,\"Y\":324}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":2}}\",\"Confidence\":99,\"DetectedText\":\"19\",\"Polygon\":[{\"X\":252,\"Y\":307},{\"X\":402,\"Y\":314},{\"X\":397,\"Y\":419},{\"X\":247,\"Y\":412}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":6}}\",\"Confidence\":99,\"DetectedText\":\"我\",\"Polygon\":[{\"X\":1616,\"Y\":301},{\"X\":1742,\"Y\":328},{\"X\":1720,\"Y\":430},{\"X\":1594,\"Y\":403}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":7}}\",\"Confidence\":96,\"DetectedText\":\"左\",\"Polygon\":[{\"X\":1607,\"Y\":479},{\"X\":1707,\"Y\":479},{\"X\":1707,\"Y\":575},{\"X\":1607,\"Y\":575}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":4}}\",\"Confidence\":53,\"DetectedText\":\"八失婚\",\"Polygon\":[{\"X\":675,\"Y\":555},{\"X\":899,\"Y\":705},{\"X\":821,\"Y\":821},{\"X\":597,\"Y\":672}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":8}}\",\"Confidence\":99,\"DetectedText\":\"XY\",\"Polygon\":[{\"X\":197,\"Y\":965},{\"X\":332,\"Y\":965},{\"X\":332,\"Y\":1093},{\"X\":197,\"Y\":1093}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":9}}\",\"Confidence\":95,\"DetectedText\":\"2014.33\",\"Polygon\":[{\"X\":367,\"Y\":1375},{\"X\":649,\"Y\":1375},{\"X\":649,\"Y\":1479},{\"X\":367,\"Y\":1479}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":10}}\",\"Confidence\":83,\"DetectedText\":\"不配洽\",\"Polygon\":[{\"X\":629,\"Y\":1862},{\"X\":823,\"Y\":1862},{\"X\":823,\"Y\":1962},{\"X\":629,\"Y\":1962}],\"WordPolygon\":[]}]}}";

                        Scale scale = scaleMapper.selectScaleById(55246l);
                        JSONArray jsonInfo = new JSONArray(scale.getCenterPoints());
                        Map<String,String>mp=JSON.parseObject(DetecteResult, new TypeReference<Map<String, String>>() {
                        });
                        Map<String,String>mpp=JSON.parseObject(mp.get("Response"), new TypeReference<Map<String, String>>() {
                        });
                        JSONArray textDetections = new JSONArray(mpp.get("TextDetections"));
                        UserInfo Data=new UserInfo();
                        Data.setId(scr.getId());
                        for (int k = 0; k < textDetections.size(); k++) {
                            JSONObject res = textDetections.getJSONObject(k);
                            int acc = res.getInt("Confidence");
                            if(acc>90) {
                                int centerX=0,centerY=0;
                                for (int t = 0; t < 4; t++) {
                                    centerX += res.getJSONArray("Polygon").getJSONObject(t).getInt("X");
                                }
                                centerX /= 4;
                                for (int t = 0; t < 4; t++) {
                                    centerY += res.getJSONArray("Polygon").getJSONObject(t).getInt("Y");
                                }
                                centerY /= 4;
                                String Detect = res.getStr("DetectedText");
                                for (int q = 0; q < jsonInfo.size(); q++) {
                                    JSONObject info = jsonInfo.getJSONObject(q);
                                    int x=info.getInt("x");
                                    int y=info.getInt("y");
                                    int l=info.getInt("length");
                                    int w=info.getInt("width");
                                    int num=info.getInt("id");
                                    if ((Math.abs(centerX - x) <= l/2)&&(Math.abs(centerY - y)<= w/2)) {
                                        Data=func(Data,num,Detect);
                                    }
                                }
                            }
                        }
                        if(Data.getName()==null){
                            Data.setName("未命名");
                        }
                        if(Data.getDateOfBorn()==null){
                            String dateString = "1949-11-11";

                            // 定义日期格式
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                // 将字符串解析为 Date 对象
                                Date date = dateFormat.parse(dateString);

                            } catch (ParseException e) {
                                // 处理解析异常
                                System.out.println("日期解析错误: " + e.getMessage());
                            }
                        }
                        System.out.println(Data);
                        userInfoService.insertUserInfo(Data);
                    }


                    overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,folderpath+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                    if(scaletemp.getType().equals("OTHER"))
                        System.out.println("OTHER");
                    else
                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,folderpath+scr.getId()+"_"+entry.getKey()+".png");
                    str = str + entry.getKey()+" ";
                }
                str = str.substring(0,str.length()-1);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeyException e) {
                throw new RuntimeException(e);
            }
            scr.setPaperId(str);
            scaleRecordMapper.updateScaleRecord(scr);
            String pidlist = scr.getPaperId();
            String folderpath = Constants.BASE_DIR+scr.getId()+File.separator;
            List<Integer> intlist = hasink.getint(pidlist);
            Map<String,Double> map = new HashMap<>();
            for(Integer i:intlist){
                Scale scale = scaleMapper.selectScaleById(i.longValue());
                Map<String,Double> maptemp = new HashMap<>();
                if(!scale.getType().equals("OTHER")){
                    maptemp  = hasink.hasink_drawexcel(scale.getType(),scale.getCenterPoints(),folderpath+scr.getId()+"_"+scale.getId()+".png");
                }
                if (maptemp != null) {
                    map.putAll(maptemp);
                }
            }
            Map<String,Double> mapresult = new HashMap<>();

            mapresult = retrunresmap(map,scr.getId());

            map.putAll(mapresult);
            //System.out.println("debug");
            //存分数
            List<Integer> pagelist = scrTotalService.insertScrTotalbymap(mapresult,scr.getId(),str, scr.getTim(), scr.getPenId());
            StringToExcel.outputexcel(map,folderpath+scr.getId()+".xlsx");
            //生成pdf
            ImageToPdfConverter.generatePDF(pagelist,scr.getId(),1);

            scr.setStatus(2l);
            scaleRecordMapper.updateScaleRecord(scr);
            System.out.println(scr.getTim());
            System.out.println(scr.getPenId());
        }

    }

    @Override
    public void handelscale_v2() throws JsonProcessingException {
        System.out.println("handling scale");
        ScaleRecord scaleRecord = new ScaleRecord();
        scaleRecord.setStatus(0l);
        List<ScaleRecord> scaleRecords = scaleRecordMapper.selectScaleRecordList(scaleRecord);
        for(ScaleRecord scr:scaleRecords){
            scr.setStatus(1l);
            scaleRecordMapper.updateScaleRecord(scr);
        }

/*        ForkJoinPool forkJoinPool = new ForkJoinPool();
        forkJoinPool.submit(() ->
                scaleRecords.parallelStream().forEach(scr -> {

                })
        ).join();
        forkJoinPool.shutdown();*/
        for (ScaleRecord scr:scaleRecords){
            String str = "";
            try {
                JSONArray jsonArray = new JSONArray(scr.getJson());

                Map<Integer,JSONArray> map = new HashMap<>();
                Map<Integer,JSONArray> mapv2 = new HashMap<>();
                PenJsonV2 penJson_2 = new PenJsonV2();
                PenJson penJson_1 = new PenJson();
                penJson_2.setScrId(scr.getId());
                penJson_1.setScrId(scr.getId());
                int counttemp = 0;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONArray subArray = jsonArray.getJSONArray(i);
                    for (int j = 0; j < subArray.size(); j++) {
                        JSONObject point = subArray.getJSONObject(j);
                        int page_id = (int) point.get("page_id");

                        if(page_id>=69130){
                            if(counttemp==0){
                                if(penJsonV2Mapper.selectPenJsonV2List(penJson_2).size()==0){
                                    counttemp++;
                                    penJsonV2Mapper.insertPenJsonV2(penJson_2);
                                }
                            }
                            if(mapv2.containsKey(page_id)){
                                JSONArray tempjsonarray = mapv2.get(page_id);
                                tempjsonarray.put(point);
                                mapv2.put(page_id,tempjsonarray);
                            }
                            else {
                                JSONArray tempjsonarray = new JSONArray();
                                tempjsonarray.put(point);
                                mapv2.put(page_id,tempjsonarray);
                            }
                        }
                        else{
                            if(counttemp==0){
                                if(penJsonMapper.selectPenJsonList(penJson_1).size()==0){
                                    counttemp++;
                                    penJsonMapper.insertPenJson(penJson_1);
                                }
                            }
                            if(map.containsKey(page_id)){
                                JSONArray tempjsonarray = map.get(page_id);
                                tempjsonarray.put(point);
                                map.put(page_id,tempjsonarray);
                            }
                            else {
                                JSONArray tempjsonarray = new JSONArray();
                                tempjsonarray.put(point);
                                map.put(page_id,tempjsonarray);
                            }
                        }
                    }
                }
                //json分页

                if(map.size()!=0){
                    for (Map.Entry<Integer, JSONArray> entry : map.entrySet()) {
                        Integer i = entry.getKey();
                        Scale scaletemp = scaleMapper.selectScaleById(Long.valueOf(i));
                        String folderpath = Constants.BASE_DIR+scr.getId()+File.separator;
                        File sourceFolder = new File(folderpath);
                        if (!sourceFolder.exists()) {
                            sourceFolder.mkdirs();
                        }
                        //存笔迹  service引入另一个servie
                        PenJson penJson = new PenJson();
                        penJson.setScrId(scr.getId());
                        List<PenJson> penJsons = penJsonMapper.selectPenJsonList(penJson);
                        iPenJsonService.insertpenjson(entry.getValue().toString(),Long.valueOf(entry.getKey().toString()),penJsons.get(0));
                        overpng(entry.getValue().toString(),folderpath+scr.getId()+"_"+entry.getKey()+".png",scaletemp.getX().intValue(),scaletemp.getY().intValue());
                        String outputPATH=Constants.NGINX_DIR+scr.getId()+"_"+entry.getKey()+".png";
//                    if(entry.getKey()==54761||entry.getKey()==54768){
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);
//                    }
                        if(entry.getKey()==55246l){//entry.getKey()==54400||entry.getKey()==54258||entry.getKey()==54259
                            //System.out.println(outputPATH);
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);

                            //String DetecteResult=OCR.GeneralHandwritingOCR(outputPATH);
                            String DetecteResult="{\"Response\":{\"Angel\":359.989990234375,\"RequestId\":\"f5a50fa8-fdaf-4d0c-b9a7-1caf93679fdb\",\"TextDetections\":[{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":1}}\",\"Confidence\":100,\"DetectedText\":\"姓名\",\"Polygon\":[{\"X\":260,\"Y\":198},{\"X\":405,\"Y\":210},{\"X\":395,\"Y\":320},{\"X\":251,\"Y\":307}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"女\",\"Polygon\":[{\"X\":703,\"Y\":212},{\"X\":815,\"Y\":212},{\"X\":815,\"Y\":312},{\"X\":703,\"Y\":312}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"123456789\",\"Polygon\":[{\"X\":848,\"Y\":235},{\"X\":1267,\"Y\":263},{\"X\":1255,\"Y\":435},{\"X\":836,\"Y\":407}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"2004-08-25\",\"Polygon\":[{\"X\":1203,\"Y\":215},{\"X\":1303,\"Y\":202},{\"X\":1318,\"Y\":310},{\"X\":1217,\"Y\":323}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":5}}\",\"Confidence\":99,\"DetectedText\":\"2004\",\"Polygon\":[{\"X\":1611,\"Y\":224},{\"X\":1773,\"Y\":224},{\"X\":1773,\"Y\":324},{\"X\":1611,\"Y\":324}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":2}}\",\"Confidence\":99,\"DetectedText\":\"19\",\"Polygon\":[{\"X\":252,\"Y\":307},{\"X\":402,\"Y\":314},{\"X\":397,\"Y\":419},{\"X\":247,\"Y\":412}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":6}}\",\"Confidence\":99,\"DetectedText\":\"我\",\"Polygon\":[{\"X\":1616,\"Y\":301},{\"X\":1742,\"Y\":328},{\"X\":1720,\"Y\":430},{\"X\":1594,\"Y\":403}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":7}}\",\"Confidence\":96,\"DetectedText\":\"左\",\"Polygon\":[{\"X\":1607,\"Y\":479},{\"X\":1707,\"Y\":479},{\"X\":1707,\"Y\":575},{\"X\":1607,\"Y\":575}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":4}}\",\"Confidence\":53,\"DetectedText\":\"八失婚\",\"Polygon\":[{\"X\":675,\"Y\":555},{\"X\":899,\"Y\":705},{\"X\":821,\"Y\":821},{\"X\":597,\"Y\":672}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":8}}\",\"Confidence\":99,\"DetectedText\":\"XY\",\"Polygon\":[{\"X\":197,\"Y\":965},{\"X\":332,\"Y\":965},{\"X\":332,\"Y\":1093},{\"X\":197,\"Y\":1093}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":9}}\",\"Confidence\":95,\"DetectedText\":\"2014.33\",\"Polygon\":[{\"X\":367,\"Y\":1375},{\"X\":649,\"Y\":1375},{\"X\":649,\"Y\":1479},{\"X\":367,\"Y\":1479}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":10}}\",\"Confidence\":83,\"DetectedText\":\"不配洽\",\"Polygon\":[{\"X\":629,\"Y\":1862},{\"X\":823,\"Y\":1862},{\"X\":823,\"Y\":1962},{\"X\":629,\"Y\":1962}],\"WordPolygon\":[]}]}}";
                            //todo 暂时不用换ocr
                            Scale scale = scaleMapper.selectScaleById(55246l);
                            JSONArray jsonInfo = new JSONArray(scale.getCenterPoints());
                            Map<String,String>mp=JSON.parseObject(DetecteResult, new TypeReference<Map<String, String>>() {
                            });
                            Map<String,String>mpp=JSON.parseObject(mp.get("Response"), new TypeReference<Map<String, String>>() {
                            });
                            JSONArray textDetections = new JSONArray(mpp.get("TextDetections"));
                            UserInfo Data=new UserInfo();
                            Data.setId(scr.getId());
                            for (int k = 0; k < textDetections.size(); k++) {
                                JSONObject res = textDetections.getJSONObject(k);
                                int acc = res.getInt("Confidence");
                                if(acc>90) {
                                    int centerX=0,centerY=0;
                                    for (int t = 0; t < 4; t++) {
                                        centerX += res.getJSONArray("Polygon").getJSONObject(t).getInt("X");
                                    }
                                    centerX /= 4;
                                    for (int t = 0; t < 4; t++) {
                                        centerY += res.getJSONArray("Polygon").getJSONObject(t).getInt("Y");
                                    }
                                    centerY /= 4;
                                    String Detect = res.getStr("DetectedText");
                                    for (int q = 0; q < jsonInfo.size(); q++) {
                                        JSONObject info = jsonInfo.getJSONObject(q);
                                        int x=info.getInt("x");
                                        int y=info.getInt("y");
                                        int l=info.getInt("length");
                                        int w=info.getInt("width");
                                        int num=info.getInt("id");
                                        if ((Math.abs(centerX - x) <= l/2)&&(Math.abs(centerY - y)<= w/2)) {
                                            Data=func(Data,num,Detect);
                                        }
                                    }
                                }
                            }
                            if(Data.getName()==null){
                                Data.setName("未命名");
                            }
                            if(Data.getDateOfBorn()==null){
                                String dateString = "1949-11-11";

                                // 定义日期格式
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                try {
                                    // 将字符串解析为 Date 对象
                                    Date date = dateFormat.parse(dateString);

                                } catch (ParseException e) {
                                    // 处理解析异常
                                    System.out.println("日期解析错误: " + e.getMessage());
                                }
                            }
                            System.out.println(Data);
                            userInfoService.insertUserInfo(Data);
                        }


                        System.out.println("---------------------small");
                        System.out.println(folderpath+scr.getId()+"_"+entry.getKey()+".png");
                        System.out.println("---------------------big");
                        System.out.println(Constants.BASE_DIR+"background_"+entry.getKey()+".png");
                        System.out.println("------------------------out");
                        System.out.println(folderpath+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,folderpath+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                        if(scaletemp.getType().equals("OTHER"))
                            System.out.println("OTHER");
                        else
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,folderpath+scr.getId()+"_"+entry.getKey()+".png");
                        str = str + entry.getKey()+" ";
                    }
                }

                if(mapv2.size()!=0){
                    for (Map.Entry<Integer, JSONArray> entry : mapv2.entrySet()) {
                        Integer i = entry.getKey();
                        ScaleV2 scaletemp2 = scaleV2Mapper.selectScaleV2ById(Long.valueOf(i));
                        String folderpath = Constants.BASE_DIR+scr.getId()+File.separator;
                        File sourceFolder = new File(folderpath);
                        if (!sourceFolder.exists()) {
                            sourceFolder.mkdirs();
                        }
                        //存笔迹  service引入另一个servie
                        PenJsonV2 penJsonV2 = new PenJsonV2();
                        penJsonV2.setScrId(scr.getId());
                        List<PenJsonV2> penJsonV2s = penJsonV2Mapper.selectPenJsonV2List(penJsonV2);
                        iPenJsonV2Service.insertpenjsonv2(entry.getValue().toString(),Long.valueOf(entry.getKey().toString()),penJsonV2s.get(0));
                        overpng(entry.getValue().toString(),folderpath+scr.getId()+"_"+entry.getKey()+".png",scaletemp2.getX().intValue(),scaletemp2.getY().intValue());
                        String outputPATH=Constants.NGINX_DIR+scr.getId()+"_"+entry.getKey()+".png";
//                    if(entry.getKey()==54761||entry.getKey()==54768){
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
//                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);
//                    }
                        if(entry.getKey()==69137l){//entry.getKey()==54400||entry.getKey()==54258||entry.getKey()==54259
                            //System.out.println(outputPATH);
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,Constants.NGINX_DIR+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,outputPATH);

                            //String DetecteResult=OCR.GeneralHandwritingOCR(outputPATH);
                            String DetecteResult="{\"Response\":{\"Angel\":359.989990234375,\"RequestId\":\"f5a50fa8-fdaf-4d0c-b9a7-1caf93679fdb\",\"TextDetections\":[{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":1}}\",\"Confidence\":100,\"DetectedText\":\"姓名\",\"Polygon\":[{\"X\":260,\"Y\":198},{\"X\":405,\"Y\":210},{\"X\":395,\"Y\":320},{\"X\":251,\"Y\":307}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"女\",\"Polygon\":[{\"X\":703,\"Y\":212},{\"X\":815,\"Y\":212},{\"X\":815,\"Y\":312},{\"X\":703,\"Y\":312}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"123456789\",\"Polygon\":[{\"X\":848,\"Y\":235},{\"X\":1267,\"Y\":263},{\"X\":1255,\"Y\":435},{\"X\":836,\"Y\":407}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":3}}\",\"Confidence\":99,\"DetectedText\":\"2004-08-25\",\"Polygon\":[{\"X\":1203,\"Y\":215},{\"X\":1303,\"Y\":202},{\"X\":1318,\"Y\":310},{\"X\":1217,\"Y\":323}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":5}}\",\"Confidence\":99,\"DetectedText\":\"2004\",\"Polygon\":[{\"X\":1611,\"Y\":224},{\"X\":1773,\"Y\":224},{\"X\":1773,\"Y\":324},{\"X\":1611,\"Y\":324}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":2}}\",\"Confidence\":99,\"DetectedText\":\"19\",\"Polygon\":[{\"X\":252,\"Y\":307},{\"X\":402,\"Y\":314},{\"X\":397,\"Y\":419},{\"X\":247,\"Y\":412}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":6}}\",\"Confidence\":99,\"DetectedText\":\"我\",\"Polygon\":[{\"X\":1616,\"Y\":301},{\"X\":1742,\"Y\":328},{\"X\":1720,\"Y\":430},{\"X\":1594,\"Y\":403}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":7}}\",\"Confidence\":96,\"DetectedText\":\"左\",\"Polygon\":[{\"X\":1607,\"Y\":479},{\"X\":1707,\"Y\":479},{\"X\":1707,\"Y\":575},{\"X\":1607,\"Y\":575}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":4}}\",\"Confidence\":53,\"DetectedText\":\"八失婚\",\"Polygon\":[{\"X\":675,\"Y\":555},{\"X\":899,\"Y\":705},{\"X\":821,\"Y\":821},{\"X\":597,\"Y\":672}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":8}}\",\"Confidence\":99,\"DetectedText\":\"XY\",\"Polygon\":[{\"X\":197,\"Y\":965},{\"X\":332,\"Y\":965},{\"X\":332,\"Y\":1093},{\"X\":197,\"Y\":1093}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":9}}\",\"Confidence\":95,\"DetectedText\":\"2014.33\",\"Polygon\":[{\"X\":367,\"Y\":1375},{\"X\":649,\"Y\":1375},{\"X\":649,\"Y\":1479},{\"X\":367,\"Y\":1479}],\"WordPolygon\":[]},{\"AdvancedInfo\":\"{\\\"Parag\\\":{\\\"ParagNo\\\":10}}\",\"Confidence\":83,\"DetectedText\":\"不配洽\",\"Polygon\":[{\"X\":629,\"Y\":1862},{\"X\":823,\"Y\":1862},{\"X\":823,\"Y\":1962},{\"X\":629,\"Y\":1962}],\"WordPolygon\":[]}]}}";
                            //todo 暂时不用换ocr
                            ScaleV2 scaleV2 = scaleV2Mapper.selectScaleV2ById(69137l);
                            JSONArray jsonInfo = new JSONArray(scaleV2.getCenterPoints());
                            Map<String,String>mp=JSON.parseObject(DetecteResult, new TypeReference<Map<String, String>>() {
                            });
                            Map<String,String>mpp=JSON.parseObject(mp.get("Response"), new TypeReference<Map<String, String>>() {
                            });
                            JSONArray textDetections = new JSONArray(mpp.get("TextDetections"));
                            UserInfoV2 Data=new UserInfoV2();
                            Data.setId(scr.getId());
                            for (int k = 0; k < textDetections.size(); k++) {
                                JSONObject res = textDetections.getJSONObject(k);
                                int acc = res.getInt("Confidence");
                                if(acc>90) {
                                    int centerX=0,centerY=0;
                                    for (int t = 0; t < 4; t++) {
                                        centerX += res.getJSONArray("Polygon").getJSONObject(t).getInt("X");
                                    }
                                    centerX /= 4;
                                    for (int t = 0; t < 4; t++) {
                                        centerY += res.getJSONArray("Polygon").getJSONObject(t).getInt("Y");
                                    }
                                    centerY /= 4;
                                    String Detect = res.getStr("DetectedText");
                                    for (int q = 0; q < jsonInfo.size(); q++) {
                                        JSONObject info = jsonInfo.getJSONObject(q);
                                        int x=info.getInt("x");
                                        int y=info.getInt("y");
                                        int l=info.getInt("length");
                                        int w=info.getInt("width");
                                        int num=info.getInt("id");
                                        if ((Math.abs(centerX - x) <= l/2)&&(Math.abs(centerY - y)<= w/2)) {
                                            Data=funcV2(Data,num,Detect);
                                        }
                                    }
                                }
                            }
                            if(Data.getName()==null){
                                Data.setName("未命名");
                            }
                            if(Data.getDateOfBorn()==null){
                                String dateString = "1949-11-11";

                                // 定义日期格式
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                try {
                                    // 将字符串解析为 Date 对象
                                    Date date = dateFormat.parse(dateString);

                                } catch (ParseException e) {
                                    // 处理解析异常
                                    System.out.println("日期解析错误: " + e.getMessage());
                                }
                            }
                            System.out.println(Data);
                            userInfoV2Service.insertUserInfoV2(Data);
                        }


                        overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_"+entry.getKey()+".png",0,0,folderpath+"base_"+scr.getId()+"_"+entry.getKey()+".png");
                        if(scaletemp2.getType().equals("OTHER"))
                            System.out.println("OTHER");
                        else
                            overpngbyX_Y(folderpath+scr.getId()+"_"+entry.getKey()+".png",Constants.BASE_DIR+"background_54762.png",0,0,folderpath+scr.getId()+"_"+entry.getKey()+".png");
                        str = str + entry.getKey()+" ";
                    }
                }


                str = str.substring(0,str.length()-1);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            scr.setPaperId(str);
            scaleRecordMapper.updateScaleRecord(scr);
            String pidlist = scr.getPaperId();
            String folderpath = Constants.BASE_DIR+scr.getId()+File.separator;
            List<Integer> intlist = hasink.getint(pidlist);
            Map<String,Double> map = new HashMap<>();
            Map<String,Double> mapv2 = new HashMap<>();
            for(Integer i:intlist){
                Scale scale = scaleMapper.selectScaleById(i.longValue());
                ScaleV2 scaleV2 = scaleV2Mapper.selectScaleV2ById(i.longValue());
                Map<String,Double> maptemp = new HashMap<>();
                Map<String,Double> maptempv2 = new HashMap<>();
                if(scale!=null&&!scale.getType().equals("OTHER")){
                    maptemp  = hasink.hasink_drawexcel(scale.getType(),scale.getCenterPoints(),folderpath+scr.getId()+"_"+scale.getId()+".png");
                }
                if (maptemp != null&&maptemp.size()!=0) {
                    map.putAll(maptemp);
                }
                if(scaleV2!=null&&!scaleV2.getType().equals("OTHER")){
                    maptempv2  = hasink.hasink_drawexcel(scaleV2.getType(),scaleV2.getCenterPoints(),folderpath+scr.getId()+"_"+scaleV2.getId()+".png");
                }
                if (maptempv2 != null&&maptempv2.size()!=0) {
                    mapv2.putAll(maptempv2);
                }
            }
            Map<String,Double> mapresult = new HashMap<>();
            Map<String,Double> mapresultv2 = new HashMap<>();


            if(map.size()!=0 ||(map.size()==0&&intlist.contains(55246)))
                mapresult = retrunresmap(map,scr.getId());
            if(mapv2.size()!=0 ||(mapv2.size()==0&&intlist.contains(69137)))
                mapresultv2 = retrunresmap(mapv2,scr.getId());


            if(mapresult.size()!=0)
                map.putAll(mapresult);
            if(mapresultv2.size()!=0)
                mapv2.putAll(mapresultv2);
            //System.out.println("debug");
            //存分数
            List<Integer> pagelist = new ArrayList<>();
            List<Integer> pagelistV2 = new ArrayList<>();
            if(mapresult.size()!=0)
                pagelist = scrTotalService.insertScrTotalbymap(mapresult,scr.getId(),str, scr.getTim(), scr.getPenId());
            if(mapresultv2.size()!=0)
                pagelistV2 = scrTotalV2Service.insertScrTotalV2bymap(mapresultv2,scr.getId(),str, scr.getTim(), scr.getPenId());


            if(map.size()!=0){
                StringToExcel.outputexcel(map,folderpath+scr.getId()+".xlsx");
                //生成pdf
                ImageToPdfConverter.generatePDF(pagelist,scr.getId(),1);
            }

            if(mapv2.size()!=0){
                System.out.println("----------------------xlxs----------------------------");
                StringToExcel.outputexcel(mapv2,folderpath+scr.getId()+"_v2.xlsx");
                //生成pdf_v2
                ImageToPdfConverter.generatePDF(pagelistV2,scr.getId(),2);
            }


            scr.setStatus(2l);
            scaleRecordMapper.updateScaleRecord(scr);
            System.out.println(scr.getTim());
            System.out.println(scr.getPenId());
        }
    }

    private UserInfo func(UserInfo Data,int num,String Detect) {
        if(num==0){
            Data.setName(Detect);
        }
        else if(num==1){
            Data.setSex("男");
        }
        else if(num==2){
            Data.setSex("女");
        }
        else if(num==3){
            if (Detect.matches("^((?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$")) {
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date =df.parse(Detect);
                    Data.setDateOfBorn(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        else if(num==4){
            Data.setHand("左手");
        }
        else if(num==5){
            Data.setHand("右手");
        }
        else if(num==6){
            Data.setHand("其它");
        }
        else if(num==7){
            Data.setContact(Detect);
        }
        else if(num==8){
            Data.setTel(Detect);
        }
        else if(num==9){
            Data.setAddress(Detect);
        }
        else if(num==10){
            Data.setMarry("已婚");
        }
        else if(num==11){
            Data.setMarry("未婚");
        }
        else if(num==12){
            Data.setMarry("丧偶");
        }
        else if(num==13){
            Data.setMarry("离异");
        }
        else if(num==14){
            Data.setMarry("其它");
        }
        else if(num==15){
            Data.setEdu("文盲和半文盲");
        }
        else if(num==16){
            Data.setEdu("小学");
        }
        else if(num==17){
            Data.setEdu("初中");
        }
        else if(num==18){
            Data.setEdu("高中");
        }
        else if(num==19){
            Data.setEdu("本科");
        }
        else if(num==20){
            Data.setEdu("研究生");
        }
        else if(num==21){
            if(Detect.matches("^[0-9]*$"))Data.setEdu(Detect);
        }
        else if(num==24){
            Data.setRelation(Detect);
        }
        return Data;
    }

    private UserInfoV2 funcV2(UserInfoV2 Data,int num,String Detect) {
        if(num==0){
            Data.setName(Detect);
        }
        else if(num==1){
            Data.setSex("男");
        }
        else if(num==2){
            Data.setSex("女");
        }
        else if(num==3){
            if (Detect.matches("^((?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$")) {
                SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date =df.parse(Detect);
                    Data.setDateOfBorn(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        else if(num==4){
            Data.setHand("左手");
        }
        else if(num==5){
            Data.setHand("右手");
        }
        else if(num==6){
            Data.setHand("其它");
        }
        else if(num==7){
            Data.setContact(Detect);
        }
        else if(num==8){
            Data.setTel(Detect);
        }
        else if(num==9){
            Data.setAddress(Detect);
        }
        else if(num==10){
            Data.setMarry("已婚");
        }
        else if(num==11){
            Data.setMarry("未婚");
        }
        else if(num==12){
            Data.setMarry("丧偶");
        }
        else if(num==13){
            Data.setMarry("离异");
        }
        else if(num==14){
            Data.setMarry("其它");
        }
        else if(num==15){
            Data.setEdu("文盲和半文盲");
        }
        else if(num==16){
            Data.setEdu("小学");
        }
        else if(num==17){
            Data.setEdu("初中");
        }
        else if(num==18){
            Data.setEdu("高中");
        }
        else if(num==19){
            Data.setEdu("本科");
        }
        else if(num==20){
            Data.setEdu("研究生");
        }
        else if(num==21){
            if(Detect.matches("^[0-9]*$"))Data.setEdu(Detect);
        }
        else if(num==24){
            Data.setRelation(Detect);
        }
        return Data;
    }


}

